<template>
  <div class="match-detail-container">
    <!-- 比赛基本信息 -->
    <el-card class="match-info-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="title">比赛详情</span>
          <div class="actions">
            <el-button @click="$router.back()">
              <IconifyIconOffline icon="ep:back" class="mr-1" />
              返回
            </el-button>
            <el-button type="primary" @click="handleEdit">
              <IconifyIconOffline icon="ep:edit" class="mr-1" />
              编辑
            </el-button>
          </div>
        </div>
      </template>

      <div class="match-content">
        <div class="match-header">
          <div class="cover-section">
            <img :src="match.cover" :alt="match.name" class="match-cover" />
          </div>

          <div class="info-section">
            <h1 class="match-title">{{ match.name }}</h1>
            <p v-if="match.subtitle" class="match-subtitle">
              {{ match.subtitle }}
            </p>

            <div class="match-meta">
              <div class="meta-item">
                <IconifyIconOffline icon="ep:trophy" class="meta-icon" />
                <span
                  >{{ getSportTypeName(match.sportType) }} ·
                  {{ getLevelName(match.level) }}</span
                >
              </div>

              <div class="meta-item">
                <IconifyIconOffline icon="ep:medal" class="meta-icon" />
                <span>{{ getMatchTypeName(match.matchType) }}</span>
              </div>

              <div class="meta-item">
                <IconifyIconOffline icon="ep:calendar" class="meta-icon" />
                <span
                  >{{ formatDateTime(match.startDate) }} -
                  {{ formatDateTime(match.endDate) }}</span
                >
              </div>

              <div class="meta-item">
                <IconifyIconOffline icon="ep:location" class="meta-icon" />
                <span
                  >{{ match.province }}{{ match.city }}{{ match.district }}
                  {{ match.address }}</span
                >
              </div>

              <div class="meta-item">
                <IconifyIconOffline
                  icon="ep:office-building"
                  class="meta-icon"
                />
                <span>{{ match.venue }}</span>
              </div>

              <div class="meta-item">
                <IconifyIconOffline icon="ep:user-filled" class="meta-icon" />
                <span
                  >{{ match.currentTeams }}/{{ match.maxTeams }} 队伍 ({{
                    match.teamSize
                  }}人/队)</span
                >
              </div>

              <div class="meta-item">
                <IconifyIconOffline icon="ep:money" class="meta-icon" />
                <span v-if="match.registrationFee === 0" class="free-tag"
                  >免费</span
                >
                <span v-else class="fee-tag"
                  >¥{{ match.registrationFee }}/队</span
                >
              </div>
            </div>

            <div class="status-section">
              <el-tag :type="getStatusType(match.status)" size="large">
                {{ getStatusText(match.status) }}
              </el-tag>

              <el-tag v-if="match.isPublic" type="success" size="large">
                公开比赛
              </el-tag>

              <el-tag v-if="match.needApproval" type="warning" size="large">
                需要审核
              </el-tag>
            </div>
          </div>
        </div>

        <div class="match-description">
          <h3>比赛介绍</h3>
          <p>{{ match.description }}</p>
        </div>

        <div v-if="match.rules" class="match-rules">
          <h3>比赛规则</h3>
          <pre class="rules-content">{{ match.rules }}</pre>
        </div>
      </div>
    </el-card>

    <!-- 时间安排 -->
    <el-card class="schedule-card" shadow="never">
      <template #header>
        <span class="title">时间安排</span>
      </template>

      <div class="schedule-content">
        <el-timeline>
          <el-timeline-item timestamp="报名阶段" placement="top" type="primary">
            <div class="timeline-content">
              <div class="timeline-title">报名时间</div>
              <div class="timeline-desc">
                {{ formatDateTime(match.registrationStartDate) }} -
                {{ formatDateTime(match.registrationEndDate) }}
              </div>
            </div>
          </el-timeline-item>

          <el-timeline-item timestamp="比赛阶段" placement="top" type="success">
            <div class="timeline-content">
              <div class="timeline-title">比赛时间</div>
              <div class="timeline-desc">
                {{ formatDateTime(match.startDate) }} -
                {{ formatDateTime(match.endDate) }}
              </div>
            </div>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-card>

    <!-- 主办方信息 -->
    <el-card class="organizer-card" shadow="never">
      <template #header>
        <span class="title">主办方信息</span>
      </template>

      <div class="organizer-content">
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="organizer-item">
              <div class="organizer-label">主办方</div>
              <div class="organizer-value">{{ match.organizer }}</div>
            </div>
          </el-col>

          <el-col v-if="match.coOrganizer" :span="8">
            <div class="organizer-item">
              <div class="organizer-label">协办方</div>
              <div class="organizer-value">{{ match.coOrganizer }}</div>
            </div>
          </el-col>

          <el-col :span="8">
            <div class="organizer-item">
              <div class="organizer-label">联系人</div>
              <div class="organizer-value">{{ match.contactName }}</div>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20" style="margin-top: 20px">
          <el-col :span="8">
            <div class="organizer-item">
              <IconifyIconOffline icon="ep:phone" class="contact-icon" />
              <div>
                <div class="organizer-label">联系电话</div>
                <div class="organizer-value">{{ match.contactPhone }}</div>
              </div>
            </div>
          </el-col>

          <el-col v-if="match.contactEmail" :span="8">
            <div class="organizer-item">
              <IconifyIconOffline icon="ep:message" class="contact-icon" />
              <div>
                <div class="organizer-label">联系邮箱</div>
                <div class="organizer-value">{{ match.contactEmail }}</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 奖项设置 -->
    <el-card class="prizes-card" shadow="never">
      <template #header>
        <span class="title">奖项设置</span>
      </template>

      <div class="prizes-content">
        <div class="prize-list">
          <div
            v-for="(prize, index) in match.prizes"
            :key="index"
            class="prize-item"
          >
            <div class="prize-rank">{{ index + 1 }}</div>
            <div class="prize-info">
              <div class="prize-name">{{ prize.name }}</div>
              <div class="prize-desc">{{ prize.description }}</div>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 参赛队伍 -->
    <el-card class="teams-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="title">参赛队伍 ({{ teams.length }})</span>
          <div class="actions">
            <el-button type="primary" size="small" @click="exportTeams">
              <IconifyIconOffline icon="ep:download" class="mr-1" />
              导出名单
            </el-button>
            <el-button type="success" size="small" @click="generateBracket">
              <IconifyIconOffline icon="ep:grid" class="mr-1" />
              生成对阵
            </el-button>
          </div>
        </div>
      </template>

      <el-table :data="teams" stripe>
        <el-table-column prop="id" label="序号" width="80" />
        <el-table-column prop="name" label="队伍名称" min-width="150" />
        <el-table-column prop="captain" label="队长" width="120" />
        <el-table-column prop="phone" label="联系电话" width="130" />
        <el-table-column prop="memberCount" label="队员数量" width="100">
          <template #default="{ row }">
            {{ row.memberCount }}/{{ match.teamSize }}
          </template>
        </el-table-column>
        <el-table-column prop="registrationTime" label="报名时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.registrationTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getTeamStatusType(row.status)">
              {{ getTeamStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          v-if="match.registrationFee > 0"
          prop="paymentStatus"
          label="支付状态"
          width="100"
        >
          <template #default="{ row }">
            <el-tag :type="getPaymentStatusType(row.paymentStatus)">
              {{ getPaymentStatusText(row.paymentStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="ranking" label="当前排名" width="100">
          <template #default="{ row }">
            <span v-if="row.ranking" class="ranking-badge"
              >#{{ row.ranking }}</span
            >
            <span v-else class="text-gray">-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="viewTeam(row)">
              查看
            </el-button>
            <el-button type="danger" link size="small" @click="removeTeam(row)">
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 比赛结果 -->
    <el-card
      v-if="match.status === 'completed'"
      class="results-card"
      shadow="never"
    >
      <template #header>
        <div class="card-header">
          <span class="title">比赛结果</span>
          <el-button type="primary" size="small" @click="viewFullResults">
            <IconifyIconOffline icon="ep:view" class="mr-1" />
            查看完整结果
          </el-button>
        </div>
      </template>

      <div class="results-content">
        <div class="podium">
          <div
            v-for="(result, index) in topResults"
            :key="index"
            class="podium-item"
            :class="`rank-${index + 1}`"
          >
            <div class="podium-rank">{{ index + 1 }}</div>
            <div class="podium-team">{{ result.teamName }}</div>
            <div class="podium-score">{{ result.score }}分</div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 操作记录 -->
    <el-card class="logs-card" shadow="never">
      <template #header>
        <span class="title">操作记录</span>
      </template>

      <el-timeline>
        <el-timeline-item
          v-for="log in operationLogs"
          :key="log.id"
          :timestamp="formatDateTime(log.createTime)"
          placement="top"
        >
          <div class="log-content">
            <div class="log-action">{{ log.action }}</div>
            <div class="log-operator">操作人：{{ log.operator }}</div>
            <div v-if="log.remark" class="log-remark">{{ log.remark }}</div>
          </div>
        </el-timeline-item>
      </el-timeline>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { IconifyIconOffline } from "@/components/ReIcon";
import dayjs from "dayjs";

const route = useRoute();
const router = useRouter();

// 比赛详情数据
const match = ref({
  id: 1,
  name: "2024年春季篮球联赛",
  subtitle: "青少年篮球比赛",
  cover:
    "https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=basketball%20tournament%20poster%2C%20youth%20competition%2C%20championship%20design&image_size=portrait_4_3",
  sportType: "basketball",
  level: "city",
  matchType: "single_elimination",
  description:
    "本次篮球联赛旨在推广篮球运动，提高青少年身体素质，培养团队合作精神。比赛采用单淘汰制，分为男子组和女子组。欢迎全市青少年篮球爱好者踊跃报名参加。",
  registrationStartDate: "2024-02-01 09:00:00",
  registrationEndDate: "2024-03-01 18:00:00",
  startDate: "2024-03-15 08:00:00",
  endDate: "2024-03-25 18:00:00",
  province: "广东省",
  city: "深圳市",
  district: "南山区",
  address: "科技园南区深南大道9988号",
  venue: "深圳湾体育中心篮球馆",
  maxTeams: 32,
  currentTeams: 16,
  teamSize: 5,
  registrationFee: 500,
  eligibility: "amateur",
  ageLimit: "16-18岁",
  genderLimit: "unlimited",
  organizer: "深圳市体育局",
  coOrganizer: "深圳市篮球协会",
  contactName: "李主任",
  contactPhone: "13800138000",
  contactEmail: "contact@sports.sz.gov.cn",
  rules:
    "1. 比赛采用FIBA最新规则\n2. 每场比赛4节，每节12分钟\n3. 暂停规则：上半场每队2次，下半场每队3次\n4. 犯规规则：个人犯规6次离场，技术犯规直接离场\n5. 服装要求：统一队服，球鞋必须是篮球鞋\n6. 比赛时间不得迟到，迟到10分钟视为弃权",
  prizes: [
    { name: "冠军", description: "奖杯 + 奖金10000元 + 证书" },
    { name: "亚军", description: "奖杯 + 奖金6000元 + 证书" },
    { name: "季军", description: "奖杯 + 奖金3000元 + 证书" },
    { name: "优秀奖", description: "证书 + 奖金1000元" }
  ],
  allowSubstitute: true,
  allowSpectator: true,
  isPublic: true,
  needApproval: false,
  status: "ongoing",
  creator: "管理员",
  createTime: "2024-01-15 10:00:00"
});

// 参赛队伍列表
const teams = ref([
  {
    id: 1,
    name: "雄鹰队",
    captain: "张强",
    phone: "13800138001",
    memberCount: 5,
    registrationTime: "2024-02-05 10:30:00",
    status: "confirmed",
    paymentStatus: "paid",
    ranking: 1
  },
  {
    id: 2,
    name: "猛虎队",
    captain: "李明",
    phone: "13800138002",
    memberCount: 5,
    registrationTime: "2024-02-06 14:20:00",
    status: "confirmed",
    paymentStatus: "paid",
    ranking: 2
  },
  {
    id: 3,
    name: "闪电队",
    captain: "王伟",
    phone: "13800138003",
    memberCount: 4,
    registrationTime: "2024-02-07 09:15:00",
    status: "pending",
    paymentStatus: "pending",
    ranking: null
  }
]);

// 比赛结果（前三名）
const topResults = ref([
  { teamName: "雄鹰队", score: 95 },
  { teamName: "猛虎队", score: 88 },
  { teamName: "神鹰队", score: 82 }
]);

// 操作记录
const operationLogs = ref([
  {
    id: 1,
    action: "创建比赛",
    operator: "管理员",
    createTime: "2024-01-15 10:00:00",
    remark: "初始创建"
  },
  {
    id: 2,
    action: "开放报名",
    operator: "管理员",
    createTime: "2024-02-01 09:00:00",
    remark: "报名通道开启"
  },
  {
    id: 3,
    action: "队伍报名",
    operator: "雄鹰队",
    createTime: "2024-02-05 10:30:00",
    remark: "在线支付成功"
  },
  {
    id: 4,
    action: "开始比赛",
    operator: "管理员",
    createTime: "2024-03-15 08:00:00",
    remark: "比赛正式开始"
  }
]);

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  return dayjs(dateTime).format("YYYY-MM-DD HH:mm");
};

// 获取运动类型名称
const getSportTypeName = (type: string) => {
  const typeMap: Record<string, string> = {
    basketball: "篮球",
    badminton: "羽毛球",
    football: "足球",
    tennis: "网球",
    pingpong: "乒乓球"
  };
  return typeMap[type] || type;
};

// 获取级别名称
const getLevelName = (level: string) => {
  const levelMap: Record<string, string> = {
    international: "国际级",
    national: "国家级",
    provincial: "省级",
    city: "市级",
    district: "区级",
    amateur: "业余级"
  };
  return levelMap[level] || level;
};

// 获取比赛类型名称
const getMatchTypeName = (type: string) => {
  const typeMap: Record<string, string> = {
    single_elimination: "单淘汰赛",
    double_elimination: "双淘汰赛",
    round_robin: "循环赛",
    swiss: "瑞士制",
    points: "积分赛"
  };
  return typeMap[type] || type;
};

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: "info",
    ongoing: "warning",
    completed: "success",
    cancelled: "danger"
  };
  return statusMap[status] || "info";
};

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: "未开始",
    ongoing: "进行中",
    completed: "已结束",
    cancelled: "已取消"
  };
  return statusMap[status] || "未知";
};

// 获取队伍状态类型
const getTeamStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    confirmed: "success",
    pending: "warning",
    rejected: "danger"
  };
  return statusMap[status] || "info";
};

// 获取队伍状态文本
const getTeamStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    confirmed: "已确认",
    pending: "待审核",
    rejected: "已拒绝"
  };
  return statusMap[status] || "未知";
};

// 获取支付状态类型
const getPaymentStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    paid: "success",
    pending: "warning",
    failed: "danger",
    refunded: "info"
  };
  return statusMap[status] || "info";
};

// 获取支付状态文本
const getPaymentStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    paid: "已支付",
    pending: "待支付",
    failed: "支付失败",
    refunded: "已退款"
  };
  return statusMap[status] || "未知";
};

// 编辑比赛
const handleEdit = () => {
  router.push(`/match/edit/${match.value.id}`);
};

// 查看队伍
const viewTeam = (team: any) => {
  ElMessage.info(`查看队伍：${team.name}`);
};

// 移除队伍
const removeTeam = async (team: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要移除队伍 "${team.name}" 吗？`,
      "确认移除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    // 这里应该调用API移除队伍
    ElMessage.success("移除成功");
  } catch {
    // 用户取消
  }
};

// 导出队伍名单
const exportTeams = () => {
  // 这里应该调用导出API
  ElMessage.success("导出成功");
};

// 生成对阵图
const generateBracket = async () => {
  try {
    await ElMessageBox.confirm(
      "生成对阵图将根据当前报名队伍自动安排比赛，确定要继续吗？",
      "确认生成对阵图",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    // 这里应该调用API生成对阵图
    ElMessage.success("对阵图生成成功");
    router.push(`/event/schedule/${match.value.id}`);
  } catch {
    // 用户取消
  }
};

// 查看完整结果
const viewFullResults = () => {
  router.push(`/match/result/${match.value.id}`);
};

// 加载比赛详情
const loadMatchDetail = async () => {
  const matchId = route.params.id;
  // 这里应该根据ID调用API获取比赛详情
  console.log("加载比赛详情:", matchId);
};

onMounted(() => {
  loadMatchDetail();
});
</script>

<style scoped lang="scss">
.match-detail-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .title {
    font-size: 18px;
    font-weight: 600;
    color: #303133;
  }

  .actions {
    display: flex;
    gap: 8px;
  }
}

.match-info-card,
.schedule-card,
.organizer-card,
.prizes-card,
.teams-card,
.results-card,
.logs-card {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.match-content {
  .match-header {
    display: flex;
    gap: 30px;
    margin-bottom: 30px;

    .cover-section {
      flex-shrink: 0;

      .match-cover {
        width: 200px;
        height: 267px;
        object-fit: cover;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      }
    }

    .info-section {
      flex: 1;

      .match-title {
        font-size: 24px;
        font-weight: 600;
        color: #303133;
        margin: 0 0 8px 0;
      }

      .match-subtitle {
        font-size: 16px;
        color: #606266;
        margin: 0 0 20px 0;
      }

      .match-meta {
        margin-bottom: 20px;

        .meta-item {
          display: flex;
          align-items: center;
          margin-bottom: 12px;

          .meta-icon {
            font-size: 16px;
            color: #909399;
            margin-right: 8px;
            width: 16px;
          }

          .free-tag {
            color: #67c23a;
            font-weight: 600;
          }

          .fee-tag {
            color: #e6a23c;
            font-weight: 600;
          }
        }
      }

      .status-section {
        display: flex;
        gap: 8px;
        flex-wrap: wrap;
      }
    }
  }

  .match-description,
  .match-rules {
    margin-bottom: 20px;

    h3 {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
      margin: 0 0 12px 0;
    }

    p {
      color: #606266;
      line-height: 1.6;
      margin: 0;
    }

    .rules-content {
      color: #606266;
      line-height: 1.6;
      margin: 0;
      white-space: pre-wrap;
      font-family: inherit;
    }
  }
}

.schedule-content {
  .timeline-content {
    .timeline-title {
      font-weight: 600;
      color: #303133;
      margin-bottom: 4px;
    }

    .timeline-desc {
      color: #606266;
      font-size: 14px;
    }
  }
}

.organizer-content {
  .organizer-item {
    display: flex;
    align-items: center;
    gap: 12px;

    .contact-icon {
      font-size: 20px;
      color: #409eff;
    }

    .organizer-label {
      font-size: 14px;
      color: #909399;
      margin-bottom: 4px;
    }

    .organizer-value {
      font-size: 16px;
      color: #303133;
      font-weight: 500;
    }
  }
}

.prizes-content {
  .prize-list {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 16px;

    .prize-item {
      display: flex;
      align-items: center;
      padding: 16px;
      background-color: #f8f9fa;
      border-radius: 8px;
      border-left: 4px solid #409eff;

      .prize-rank {
        width: 40px;
        height: 40px;
        background-color: #409eff;
        color: white;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 600;
        margin-right: 12px;
      }

      .prize-info {
        flex: 1;

        .prize-name {
          font-weight: 600;
          color: #303133;
          margin-bottom: 4px;
        }

        .prize-desc {
          font-size: 14px;
          color: #606266;
        }
      }
    }
  }
}

.ranking-badge {
  background-color: #409eff;
  color: white;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
}

.text-gray {
  color: #c0c4cc;
}

.results-content {
  .podium {
    display: flex;
    justify-content: center;
    gap: 20px;

    .podium-item {
      text-align: center;
      padding: 20px;
      border-radius: 8px;
      min-width: 120px;

      &.rank-1 {
        background: linear-gradient(135deg, #ffd700, #ffed4e);
        transform: scale(1.1);
      }

      &.rank-2 {
        background: linear-gradient(135deg, #c0c0c0, #e8e8e8);
      }

      &.rank-3 {
        background: linear-gradient(135deg, #cd7f32, #daa520);
      }

      .podium-rank {
        font-size: 24px;
        font-weight: 700;
        color: #333;
        margin-bottom: 8px;
      }

      .podium-team {
        font-size: 16px;
        font-weight: 600;
        color: #333;
        margin-bottom: 4px;
      }

      .podium-score {
        font-size: 14px;
        color: #666;
      }
    }
  }
}

.log-content {
  .log-action {
    font-weight: 600;
    color: #303133;
    margin-bottom: 4px;
  }

  .log-operator {
    font-size: 12px;
    color: #909399;
    margin-bottom: 2px;
  }

  .log-remark {
    font-size: 12px;
    color: #606266;
  }
}

@media (max-width: 768px) {
  .match-detail-container {
    padding: 10px;
  }

  .match-header {
    flex-direction: column;
    gap: 20px;

    .cover-section .match-cover {
      width: 100%;
      max-width: 200px;
      height: auto;
    }
  }

  .card-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;

    .actions {
      width: 100%;
      justify-content: flex-end;
    }
  }

  .prize-list {
    grid-template-columns: 1fr;
  }

  .podium {
    flex-direction: column;
    align-items: center;

    .podium-item {
      &.rank-1 {
        transform: none;
      }
    }
  }
}
</style>
